﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table=FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
//using POS.Plugins;
using FCNS.Data;
using System.Collections.ObjectModel;

namespace POS
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void Init()
        {
            if (!InitPosNO())
                System.Environment.Exit(0);

            InitUI();
            InitDateTime();
            InitEvent();
            InitTemplete();
            LoadTemplete();
            InitCheckDateIsChangedEvent();
        }

        private void InitUI()
        { 
            App.BackgroundBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(DoubleHConfig.AppConfig.PosBackgroundColor));
            App.ForegroundBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(DoubleHConfig.AppConfig.PosForegroundColor));

            if (DoubleHConfig.AppConfig.PosFullScreen)
            {
                this.WindowStyle = WindowStyle.None;
                this.WindowState = WindowState.Maximized;
            }
            else
            {
                this.WindowStyle = WindowStyle.ThreeDBorderWindow;
                this.WindowStartupLocation = WindowStartupLocation.Manual;
                this.WindowState = WindowState.Normal;
                this.Top = DoubleHConfig.AppConfig.PosTop;
                this.Left = DoubleHConfig.AppConfig.PosLeft;
                this.Width = DoubleHConfig.AppConfig.PosWidth;
                this.Height = DoubleHConfig.AppConfig.PosHeight;
            }

            this.Background = App.BackgroundBrush;
            this.Foreground = App.ForegroundBrush;
            this.FontSize = 22;
            foreach (UIElement ui in mainGrid.Children)
            {
                Control c = ui as Control;
                if (c != null)
                {
                    c.Background = App.BackgroundBrush;
                    c.Foreground = App.ForegroundBrush;
                }
            }

            if (App.OffLine)
                onlineMode.Content = "脱机模式";
        }

        private bool InitPosNO()
        {
            //机器号
            App.Pos = Table.PosS.GetObject(DoubleHConfig.AppConfig.PosNO);
            if (App.Pos == null || App.Pos.Id == -1)
            {
                PosNOconfig pn = new PosNOconfig();
                pn.Init();
                pn.ShowDialog();
                App.Pos = pn.Order;
            }
            if (App.Pos == null)
            {
                MessageWindow.Show("请增加POS客户端资料");
                return false;
            }

            if (App.Pos.Enable != Table.PosS.EnumEnable.启用)
            {
                MessageWindow.Show("请到后台更新POS客户端状态");
                return false;
            }

            labelPosNO.Content += DoubleHConfig.AppConfig.PosNO;
            this.Title = FCNS.Data.DbDefine.SystemName;
            return true;
        }

        private void InitDateTime()
        {
            labelDateTime.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = 60000;
            t.Tick += (ss, ee) =>
            {
                labelDateTime.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                ForceJiaoBanNow();
            };

            t.Start();
        }

        private void InitEvent()
        {
            frame1.Navigating += (ss, ee) => RealyNavigating(ee);
            this.Closing += (ss, ee) => PosClosing(ee); 
            labelPosNO.MouseDoubleClick += (ss, ee) => ClearPosConfig();
        }

        private void ClearPosConfig()
        {
            if(MessageWindow.Show("","清空POS链接信息软件会强行关闭,确定继续吗?",MessageBoxButton.YesNo)==MessageBoxResult.No)
                return;

           DoubleHConfig.AppConfig.PosNO=string.Empty;
           DoubleH.Utility.Configuration.ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, DbDefine.appConfigFile);
                System.Environment.Exit(0);
        }

        private void RealyNavigating(NavigatingCancelEventArgs ee)
        {
            //防止通过键盘的 backspace 键导航页面
            if (ee.Content is ILoginTemplete && Table.UserS.LoginUser != null)
                ee.Cancel = true;
        }

        private void PosClosing(System.ComponentModel.CancelEventArgs ee)
        {
            if (MessageWindow.Show("", "是否要关闭POS系统" + (guaDanList.Count > 0 ? "，未处理的挂单将清除。" : ""), MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                ee.Cancel = true;
                return;
            }
             
            if (!DoubleHConfig.AppConfig.PosFullScreen)
            {
                DoubleHConfig.AppConfig.PosLeft = this.Left;
                DoubleHConfig.AppConfig.PosTop = this.Top;
                DoubleHConfig.AppConfig.PosWidth = this.Width;
                DoubleHConfig.AppConfig.PosHeight = this.Height;
            }
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, DbDefine.appConfigFile);
            if (Table.UserS.LoginUser != null)
                ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);

            UnInitHotKey(); 
        }

        /// <summary>
        /// 如果系统日期被更改了，就强制关闭系统。
        /// </summary>
        private void InitCheckDateIsChangedEvent()
        {
            Microsoft.Win32.SystemEvents.TimeChanged += (ss, ee) =>
            {
                if (DateTime.Now.Date != Table.SysConfig.SysConfigParams.LastLoginDate.Date)
                    System.Environment.Exit(0);
            };
        }


        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            InitHotKey();
        }

        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle)
        {
            if (!currentTemplete.IsTouch)
                KeyDowned(wParam.ToInt32());

            return IntPtr.Zero;
        }

        private void InitHotKey()
        {
            if (currentTemplete.IsTouch)
                return;

            IntPtr handle = new WindowInteropHelper(this).Handle;
            WindowsUtility.RegisterHotKey(handle, 0x9902, System.Windows.Forms.Keys.F2);
            WindowsUtility.RegisterHotKey(handle, 0x9903, System.Windows.Forms.Keys.F3);
            WindowsUtility.RegisterHotKey(handle, 0x9904, System.Windows.Forms.Keys.F4);
            WindowsUtility.RegisterHotKey(handle, 0x9905, System.Windows.Forms.Keys.F5);
            WindowsUtility.RegisterHotKey(handle, 0x9906, System.Windows.Forms.Keys.F6);
            WindowsUtility.RegisterHotKey(handle, 0x9907, System.Windows.Forms.Keys.F7);
            WindowsUtility.RegisterHotKey(handle, 0x9908, System.Windows.Forms.Keys.F8);
            WindowsUtility.RegisterHotKey(handle, 0x9909, System.Windows.Forms.Keys.F9);
            WindowsUtility.RegisterHotKey(handle, 0x9910, System.Windows.Forms.Keys.F10);
            WindowsUtility.RegisterHotKey(handle, 0x9911, System.Windows.Forms.Keys.F11);

            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);
        }

        private void UnInitHotKey()
        {
            if (currentTemplete.IsTouch)
                return;

            IntPtr handle = new WindowInteropHelper(this).Handle;
            WindowsUtility.UnregisterHotKey(handle, 0x9902);
            WindowsUtility.UnregisterHotKey(handle, 0x9903);
            WindowsUtility.UnregisterHotKey(handle, 0x9904);
            WindowsUtility.UnregisterHotKey(handle, 0x9905);
            WindowsUtility.UnregisterHotKey(handle, 0x9906);
            WindowsUtility.UnregisterHotKey(handle, 0x9907);
            WindowsUtility.UnregisterHotKey(handle, 0x9908);
            WindowsUtility.UnregisterHotKey(handle, 0x9909);
            WindowsUtility.UnregisterHotKey(handle, 0x9910);
            WindowsUtility.UnregisterHotKey(handle, 0x9911);
        }

        private void KeyDowned(int key)
        {
            if (!this.IsActive)
                return;

            if (key == 0x9902)
                CloseThis();

            if (Table.UserS.LoginUser == null)//防止为登录状态下触发其它的热键功能
                return;

            switch (key)
            {
                case 0x9911: ChangedPayMode(); break;
                case 0x9910: App.SysConfig(); break;
                case 0x9909: pSale_JiaoBan(); break;
                case 0x9908: ChangeMode(); break;
                case 0x9907: pSale_ZengSong(); break;
                case 0x9906: OpenCashbox(); break;
                case 0x9905: pSale_GuaDan(true, true, null); break;
                case 0x9904: CancelOrderByHotKey(); break;
                case 0x9903: LogOff(true); break;
            }
        }
    }
}